import { atomWithProxy } from 'jotai-valtio';
import { proxy, subscribe } from 'valtio';

import i18n from '@/locales/i18n';

export interface SupportLanguage {
  language: 'zh-CN' | 'en-US';
}

const defaultLanguage = 'zh-CN';

// 初始化国际化环境
const initLocaleProxy = (): SupportLanguage => {
  const language = localStorage.getItem('language');
  if (!language) {
    localStorage.setItem('language', defaultLanguage);
    i18n.changeLanguage(defaultLanguage);
    return { language: defaultLanguage };
  } else {
    i18n.changeLanguage(language);
    return { language } as SupportLanguage;
  }
};

export const localeProxy = proxy<SupportLanguage>(initLocaleProxy());

// 每当环境改变时则修改webstorage
subscribe(localeProxy, () => {
  localStorage.setItem('language', localeProxy.language);
  i18n.changeLanguage(localeProxy.language);
});

export default atomWithProxy(localeProxy);
